import { defineStore } from "pinia"
import axios from 'axios'
import { handleError } from '@/plugins/err-handle'
import LS from '@/plugins/localstorage'

export const useAuthStore = defineStore("auth", {
  state: () => ({
    username: '',
    password: '',
  }),
  getters: {
    // doubleCount: (state) => state.counter + 2,
  },
  actions: {
    // 登录
    login(data) {
      return new Promise((resolve, reject) => {
        console.log("login form:", data, data.username, data.password)
        // 表单数据
        let formData = new FormData()
        formData.append('username', data.username)
        formData.append('password', data.password)

        axios.post('/admin/login', formData)
          .then((response) => {
            console.log('auth store: ', response) 

            LS.set('token', response.data.access_token)
            resolve(response)
          })
          .catch((err) => {
            handleError(err)
            reject(err)
          })
        })
    },
    // 登出
    logout() {
      LS.remove('token')
      return true
    },

  },
})